<template>
  <div class="animate__animated animate__fadeInUp animate__faster">
    <div class="name wrap" :class="{ error: !checkout.status }">{{ checkout.name }}</div>
    <div class="form">
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-form-item prop="username" v-if="!account" class="animate__animated animate__fadeInDown animate__faster">
          <el-input ref="inputUsername" size="large" v-model="form.username" :placeholder="lang.t('page.index.username')" @keyup.enter="() => inputPassword.empty(true)" />
        </el-form-item>
        <el-form-item prop="password">
          <Password ref="inputPassword" size="large" @over="value => { form.password = value; onLogin() }" />
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ref, reactive, nextTick, watch } from 'vue'
import app from '@/app'
import accountModel from '@/model/account'

import Password from '@/components/password'

export default {
  components: {
    Password
  },
  props: [
    'account',
    'checkout'
  ],
  setup(props) {
    // 操作员输入框
    const inputUsername = ref(null)
    const inputPassword = ref(null)

    // 表单
    const formRef = ref(null)
    const form = reactive({
      username: '',
      password: '',
      checkout: app.tokenCheckout()
    })

    // 验证
    const rules = {
      username: [
        { required: true, message: ' ', trigger: 'blur' }
      ],
      password: [
        { required: true, message: ' ', trigger: 'blur' }
      ],
    }

    // 登陆
    let loginStatus = false
    const onLogin = () => {
      if(loginStatus) return
      formRef.value.validate(valid => {
        if (valid) {
          loginStatus = true
          accountModel.login(form).catch(() => {
            // 密码清空
            inputPassword.value.empty(true)
            loginStatus = false
          })
        }
      })
    }

    // 检查交互
    const onInput = () => {
      nextTick(() => {
        if(props.account) {
          // 选择帐号，焦点到密码
          form.username = props.account
          inputPassword.value.empty(true)
        } else {
          // 帐号获得焦点
          form.username = ''
          inputUsername.value.focus()
        }
      })
    }

    onInput()
    watch(() => props.account, () => onInput())

    return {
      lang: app.lang,

      inputPassword,
      inputUsername,
      formRef,
      form,
      rules,
      onLogin,

      onInput
    }
  }
}
</script>